﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Web;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.HSSF.UserModel;

namespace Discuz.Common
{
    public class ExcelOp
    {
        /// <summary>
        ///  <br>excel文件读取到DataSet</br>
        /// <br>2008-07-22 ljx</br>
        /// </summary>       
        /// <param name="filepath">Excel文件路径</param>
        /// <param name="sheetname">Excel文件中的表</param>
        public static DataSet ExcelDataSet(string filepath, string sheetname,string coulms)
        {
            string strConn;
            DataSet ds = new DataSet();
            strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";
            //
           // strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';";
            OleDbConnection conn = new OleDbConnection(strConn);
            try
            {
                conn.Open();
                OleDbDataAdapter oada = new OleDbDataAdapter("select " + coulms + " from [" + sheetname + "]", strConn);
                //OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + sheetname + "]", strConn);
                oada.Fill(ds);

                oada.Dispose();
                return ds;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }
        
        /// <summary>
        /// 复制EXECel到新路径
        /// </summary>
        /// <param name="TemplatePath">模版的路径</param>
        /// <param name="copyfilePath">被复制到的地址</param>
        /// <returns></returns>
        public static bool CloneExcelFormTemplete(string TemplatePath, string copyfilePath)
        {
            try
            {
                System.IO.File.Copy(TemplatePath, copyfilePath, true);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }

        #region 为同时适应03,07,10 。还有表名不固定问题
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static DataSet getDataForExecl(string filepath, bool isGetColumName)
        {
            if (filepath.Contains(".txt"))
            {
                return readTxtInfo(filepath);
            }
            string strConn;
            DataSet ds = new DataSet();
            if (filepath.Contains(".xlsx"))
            {
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';";
            }
            else
            {
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';";
            }
            OleDbConnection conn = new OleDbConnection(strConn);
            try
            {
                conn.Open();
                DataTable dtSchema = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);

                //if (!sheetname.Contains("$"))
                //{
                //    sheetname = sheetname + "$";
                //}
                if (isGetColumName)
                {
                    OleDbDataAdapter oada;
                    for (int i = 0; i < dtSchema.Rows.Count; i++)
                    {
                        string sheetname = dtSchema.Rows[i][2].ToString().Trim();
                        oada = new OleDbDataAdapter("select top 1 * from [" + sheetname + "]", strConn);
                        oada.Fill(ds);
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            break;
                        }
                        oada.Dispose();
                    }


                }
                else
                {
                    OleDbDataAdapter oada;
                    for (int i = 0; i < dtSchema.Rows.Count; i++)
                    {
                        string sheetname = dtSchema.Rows[i][2].ToString().Trim();
                        oada = new OleDbDataAdapter("select  * from [" + sheetname + "]", strConn);
                        oada.Fill(ds);
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            break;
                        }
                        oada.Dispose();
                    }


                }


                return ds;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }
        /// <summary>
        /// 获取txt的号码返回DataSet
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static DataSet readTxtInfo(string path)
        {

            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            //用户姓名,手机号码,用户生日,性别
            dt.Columns.Add(new DataColumn("姓名", System.Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("手机号码", System.Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("用户生日", System.Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("性别", System.Type.GetType("System.String")));
            using (StreamReader sr = new StreamReader(path))
            {
                try
                {

                    while (sr.Peek() >= 0)
                    {
                        DataRow dr = dt.NewRow();
                        string phone = sr.ReadLine();
                        dr[0] = phone.Trim();
                        dr[1] = phone.Trim();
                        dr[2] = "1901-1-1";
                        dr[3] = "未知";
                        dt.Rows.Add(dr);
                    }
                    sr.Close();
                    sr.Dispose();
                }
                catch { }
            }
            ds.Tables.Add(dt);
            return ds;
        }
        #endregion


        /// <summary>
        /// DataTable导出到Excel的MemoryStream
        /// </summary>
        /// <param name="dtSource">源DataTable</param>  
        /// <param name="strHeaderText">表头文本</param>  
        /// <returns></returns>
        public MemoryStream ExportExcelFromDataTable(DataTable dtSource, string strHeaderText = null)
        {
            return ExportExcelFromDataTable(dtSource, strHeaderText, -1);
        }

        /// <summary>
        /// DataTable导出到Excel的MemoryStream(NPIO)
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="strHeaderText">表头文本</param>
        /// <param name="cellBackgroundColorIndex">NPOI.HSSF.Util.HSSFColor.Green.Index 颜色枚举</param>
        /// <returns></returns>
        public MemoryStream ExportExcelFromDataTable(DataTable dtSource, string strHeaderText = null, short cellBackgroundColorIndex = NPOI.HSSF.Util.HSSFColor.Green.Index)
        {
            var workbook = new HSSFWorkbook();
            var sheet = workbook.CreateSheet();

            #region 右击文件 属性信息
            //{  
            //    DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();  
            //    dsi.Company = "http://www.yongfa365.com/";  
            //    workbook.DocumentSummaryInformation = dsi;  

            //    SummaryInformation si = PropertySetFactory.CreateSummaryInformation();  
            //    si.Author = "xwf"; //填加xls文件作者信息  
            //    si.ApplicationName = "NPOI测试程序"; //填加xls文件创建程序信息  
            //    si.LastAuthor = "xwf2"; //填加xls文件最后保存者信息  
            //    si.Comments = "说明信息"; //填加xls文件作者信息  
            //    si.Title = "NPOI测试"; //填加xls文件标题信息  
            //    si.Subject = "NPOI测试Demo";//填加文件主题信息  
            //    si.CreateDateTime = DateTime.Now;  
            //    workbook.SummaryInformation = si;  
            //}
            #endregion

            var dateStyle = workbook.CreateCellStyle();
            var format = workbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");

            //取得列宽  
            var arrColWidth = new int[dtSource.Columns.Count];
            foreach (DataColumn item in dtSource.Columns)
            {
                arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
            }
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
                    if (intTemp > arrColWidth[j])
                    {
                        arrColWidth[j] = intTemp;
                    }
                }
            }

            int rowIndex = 0;
            foreach (DataRow row in dtSource.Rows)
            {
                #region 新建表，填充表头，填充列头，样式
                if (rowIndex == 65535 || rowIndex == 0)
                {
                    if (rowIndex != 0)
                    {
                        sheet = workbook.CreateSheet();
                    }

                    #region 表头及样式
                    {
                        var headerRow = sheet.CreateRow(0);
                        headerRow.HeightInPoints = 25;
                        headerRow.CreateCell(0).SetCellValue(strHeaderText);

                        var headStyle = workbook.CreateCellStyle();
                        headStyle.Alignment = HorizontalAlignment.Center;
                        var font = workbook.CreateFont();
                        font.FontHeightInPoints = 20;
                        font.Boldweight = 700;
                        headStyle.SetFont(font);

                        headerRow.GetCell(0).CellStyle = headStyle;

                        sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
                        //headerRow.Dispose();  
                    }
                    #endregion


                    #region 列头及样式
                    {
                        var headerRow = sheet.CreateRow(1);


                        var headStyle = workbook.CreateCellStyle();
                        headStyle.Alignment = HorizontalAlignment.Center;

                        if (cellBackgroundColorIndex != -1)
                        {
                            //设置背景色
                            headStyle.FillPattern = FillPattern.SolidForeground;
                            headStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Green.Index;
                        }


                        var font = workbook.CreateFont();
                        font.FontHeightInPoints = 10;
                        font.Boldweight = 700;
                        headStyle.SetFont(font);


                        foreach (DataColumn column in dtSource.Columns)
                        {
                            headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                            headerRow.GetCell(column.Ordinal).CellStyle = headStyle;

                            //设置列宽  
                            try
                            {
                                sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
                            }
                            catch { }

                        }
                        //headerRow.Dispose();  
                    }
                    #endregion

                    rowIndex = 2;
                }
                #endregion

                #region 填充内容
                var dataRow = sheet.CreateRow(rowIndex);


                foreach (DataColumn column in dtSource.Columns)
                {
                    var newCell = dataRow.CreateCell(column.Ordinal);
                    //  newCell.CellStyle.Alignment = HorizontalAlignment.Center;
                    var drValue = row[column].ToString();

                    switch (column.DataType.ToString())
                    {
                        case "System.String"://字符串类型  
                            newCell.SetCellValue(drValue);
                            break;
                        case "System.DateTime"://日期类型  
                            DateTime dateV;
                            DateTime.TryParse(drValue, out dateV);
                            newCell.SetCellValue(dateV);

                            newCell.CellStyle = dateStyle;//格式化显示  
                            break;
                        case "System.Boolean"://布尔型  
                            bool boolV = false;
                            bool.TryParse(drValue, out boolV);
                            newCell.SetCellValue(boolV);
                            break;
                        case "System.Int16"://整型  
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int intV = 0;
                            int.TryParse(drValue, out intV);
                            newCell.SetCellValue(intV);
                            break;
                        case "System.Decimal"://浮点型  
                        case "System.Double":
                            double doubV = 0;
                            double.TryParse(drValue, out doubV);
                            newCell.SetCellValue(doubV);
                            break;
                        case "System.DBNull"://空值处理  
                            newCell.SetCellValue("");
                            break;
                        default:
                            newCell.SetCellValue("");
                            break;
                    }

                }
                #endregion

                rowIndex++;
            }

            using (var ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;

                // sheet.Dispose();  
                //workbook.Dispose();//一般只用写这一个就OK了，他会遍历并释放所有资源，但当前版本有问题所以只释放sheet  
                return ms;
            }
        }
    }
}
